/**
 * 
 */
package com.quiz.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.quiz.model.Question;


/**
 *
 * @author Brian Boyle
 * Apr 12, 2012
 */
public class QuestionDataSource extends QuizDataSource {

    public QuestionDataSource(Context context) {
        super(context);
    }

    private String getLevel(long sectionId) {
        if (sectionId == 1 || sectionId == 2) {
            return "1";
        } else if (sectionId == 3 || sectionId == 4) {
            return "2";
        } else if (sectionId == 5 || sectionId == 6) {
            return "3";
        }
        return "1";
    }

    public Question getRandomQuestion(long sectionId) {
        String sql = "SELECT * FROM QUESTION WHERE ASKED = 0 AND LEVEL = " + getLevel(sectionId) + " Order BY RANDOM() LIMIT 1";
        Cursor cursor = getDatabase().rawQuery(sql, null);
        //If all the questions have been asked, just reset their count number to zero
        if (cursor.getCount() == 0) {
            resetAskedQuestions();
            cursor.close();
            return getRandomQuestion(sectionId);
        }
        Question question = convertCursorToQuestion(cursor);
        cursor.close();
        return question;
    }

    public void updateQuestionToAsked(long questionId) {
        String whereClause = Question.COLUMN_ID + " = " + questionId;
        ContentValues contentValues = new ContentValues();
        contentValues.put(Question.COLUMN_ASKED, 1);
        getDatabase().update(Question.TABLE_NAME, contentValues, whereClause, null);
    }

    public void resetAskedQuestions() {
        ContentValues contentValues = new ContentValues();
        contentValues.put(Question.COLUMN_ASKED, 0);
        getDatabase().update(Question.TABLE_NAME, contentValues, null, null);
    }

    private Question convertCursorToQuestion(Cursor cur) {
        cur.moveToFirst();
        return new Question(cur.getLong(0), cur.getString(1), cur.getString(2), cur.getString(3), cur.getString(4), cur.getString(5), cur.getInt(6));
    }
}
